<?php

namespace common\models\site;

use Yii;

/**
 * This is the model class for table "{{%site_chm}}".
 *
 * @property int $id
 * @property int $category_id 分类ID
 * @property string|null $name 系统识别名
 * @property int $site_id 站点ID
 * @property string $title 标题
 * @property string|null $thumb 内容封面
 * @property int $listorder 显示排序
 * @property int $recommend_at 推荐时间
 * @property int $views 浏览次数
 * @property int $usefuls 觉得有用人数
 * @property int $useless 感觉无用人数
 * @property string|null $template 自定义模板
 * @property int $admin_id 管理员ID
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 */
class SiteChm extends \common\db\ActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%site_chm}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['category_id', 'site_id', 'listorder', 'recommend_at', 'views', 'usefuls', 'useless', 'admin_id', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['title'], 'required'],
            [['name', 'thumb'], 'string', 'max' => 255],
            [['title'], 'string', 'max' => 64],
            [['template'], 'string', 'max' => 50],
            [['name', 'site_id'], 'unique', 'targetAttribute' => ['name', 'site_id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'category_id' => '分类ID',
            'name' => '系统识别名',
            'site_id' => '站点ID',
            'title' => '标题',
            'thumb' => '内容封面',
            'listorder' => '显示排序',
            'recommend_at' => '推荐时间',
            'views' => '浏览次数',
            'usefuls' => '觉得有用人数',
            'useless' => '感觉无用人数',
            'template' => '自定义模板',
            'admin_id' => '管理员ID',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    /**
     * 关联站点
     * @return \common\db\ActiveQuery
     */
    public function getSite() {
        return $this->hasOne(Site::class, ['id' => 'site_id']);
    }

    /**
     * 关联子项内容条目
     * @return \common\db\ActiveQuery
     */
    public function getContent() {
        return $this->hasMany(SiteChmData::class, ['chm_id' => 'id']);
    }

    public static function findOfSite($alias = 't', $condition = []) {
        $query = static::find();
        if ($alias) {
            $query->alias($alias);
            $alias .= '.';
        }
        $query->joinWith('site site');
        $query->andWhere([
            'site.name' => Yii::$app->id,
        ]);
        $query->andFilterWhere($condition);
        return $query;
    }

}
